import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, message, Modal, Tag, Space } from 'antd';
import { PlusOutlined, ExclamationCircleOutlined, UserOutlined, DollarOutlined, DeleteOutlined } from '@ant-design/icons';
import {
  getCustomerContracts,
  createCustomerContract,
  updateCustomerContract,
  terminateContract
} from '@/services/customerContract';
import ContractForm from './components/ContractForm';
import dayjs from 'dayjs';

const CustomerContract = () => {
  const [activeTab, setActiveTab] = useState('正常');
  const [formVisible, setFormVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState(null);
  const [summaryData, setSummaryData] = useState({
    totalCustomers: 0,
    totalMonthlyFee: 0,
  });
  const actionRef = useRef();

  // 列状态管理 - 控制哪些列默认隐藏
  const [columnsStateMap, setColumnsStateMap] = useState({
    salesperson: {
      show: false, // 接单人默认隐藏
    },
    signDate: {
      show: false, // 签单日期默认隐藏
    },
    accountant: {
      show: false, // 记账会计默认隐藏
    },
    monthlyFee: {
      show: false, // 月收费默认隐藏
    },
    serviceYears: {
      show: false, // 伴龄默认隐藏
    },
  });

  // 计算合计数据
  const calculateSummary = (data) => {
    const totalCustomers = data.length;
    const totalMonthlyFee = data.reduce((sum, item) => {
      return sum + (item.contractMonthlyFee || 0);
    }, 0);

    setSummaryData({
      totalCustomers,
      totalMonthlyFee,
    });
  };

  // 表格列配置
  const columns = [
    {
      title: '客户编号',
      dataIndex: 'customerCode',
      width: 100,
      fixed: 'left',
      search: {
        transform: (value) => ({ customerCode: value }),
      },
    },
    {
      title: '客户名称',
      dataIndex: 'customerName',
      width: 150,
      fixed: 'left',
      search: {
        transform: (value) => ({ customerName: value }),
      },
    },
    {
      title: '客户评级',
      dataIndex: 'customerRating',
      width: 80,
      valueType: 'select',
      valueEnum: {
        'A+': { text: 'A+' },
        'A': { text: 'A' },
        'B+': { text: 'B+' },
        'B': { text: 'B' },
        'C': { text: 'C' },
      },
      render: (rating) => {
        const color = rating === 'A+' ? 'gold' : rating === 'A' ? 'green' : rating === 'B+' ? 'blue' : 'default';
        return <Tag color={color}>{rating}</Tag>;
      },
    },
    {
      title: '公司类型',
      dataIndex: 'companyType',
      width: 120,
      valueType: 'select',
      valueEnum: {
        '有限责任公司': { text: '有限责任公司' },
        '股份有限公司': { text: '股份有限公司' },
        '个体工商户': { text: '个体工商户' },
        '合伙企业': { text: '合伙企业' },
        '其他': { text: '其他' },
      },
    },
    {
      title: '接单人',
      dataIndex: 'salesperson',
      width: 100,
    },
    {
      title: '合同月收费',
      dataIndex: 'contractMonthlyFee',
      width: 120,
      hideInSearch: true,
      render: (fee) => `¥${fee?.toLocaleString()}`,
      sorter: true,
    },
    {
      title: '合同状态',
      dataIndex: 'contractStatus',
      width: 100,
      valueType: 'select',
      valueEnum: {
        '正常': { text: '正常', status: 'Success' },
        '终止': { text: '终止', status: 'Error' },
      },
      render: (status) => {
        const color = status === '正常' ? 'success' : status === '终止' ? 'error' : 'default';
        return <Tag color={color}>{status}</Tag>;
      },
    },
    {
      title: '服务项目',
      dataIndex: 'serviceItems',
      width: 200,
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '区域',
      dataIndex: 'area',
      width: 150,
      valueType: 'select',
      valueEnum: {
        '北京': { text: '北京' },
        '上海': { text: '上海' },
        '广州': { text: '广州' },
        '深圳': { text: '深圳' },
        '杭州': { text: '杭州' },
        '其他': { text: '其他' },
      },
    },
    {
      title: '回款计划',
      dataIndex: 'paymentPlan',
      width: 120,
      hideInSearch: true,
    },
    {
      title: '收款单',
      dataIndex: 'receiptStatus',
      width: 100,
      hideInSearch: true,
      render: (status) => {
        const color = status === '已收款' ? 'success' : status === '待收款' ? 'warning' : 'error';
        return <Tag color={color}>{status}</Tag>;
      },
    },
    {
      title: '客户状态',
      dataIndex: 'customerStatus',
      width: 100,
      hideInSearch: true,
      render: (status) => {
        const color = status === '正常' ? 'success' : status === '重点客户' ? 'gold' : 'default';
        return <Tag color={color}>{status}</Tag>;
      },
    },
    {
      title: '签单日期',
      dataIndex: 'signDate',
      width: 120,
      valueType: 'date',
      hideInSearch: true,
    },
    {
      title: '联系人',
      dataIndex: 'contactPerson',
      width: 100,
      search: {
        transform: (value) => ({ contactPerson: value }),
      },
    },
    {
      title: '联系人手机号',
      dataIndex: 'contactPhone',
      width: 140,
      search: {
        transform: (value) => ({ contactPhone: value }),
      },
    },
    {
      title: '记账会计',
      dataIndex: 'accountant',
      width: 100,
    },
    {
      title: '月收费',
      dataIndex: 'monthlyFee',
      width: 120,
      hideInSearch: true,
      render: (fee) => `¥${fee?.toLocaleString()}`,
      sorter: true,
    },
    {
      title: '到期月数',
      dataIndex: 'expirationMonths',
      width: 100,
      hideInSearch: true,
      render: (months) => `${months}月`,
    },
    {
      title: '伴龄',
      dataIndex: 'serviceYears',
      width: 80,
      hideInSearch: true,
      render: (years) => `${years}年`,
      sorter: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: activeTab === '正常' ? 100 : 100,
      fixed: 'right',
      render: (_, record) => {
        if (activeTab === '终止') {
          return (
            <Button
              type="link"
              size="small"
              onClick={() => handleRestore(record)}
              style={{ color: '#52c41a' }}
            >
              恢复
            </Button>
          );
        }

        return (
          <Space>

            <Button
              type="link"
              size="small"
              onClick={() => handleCreate(record)}
              style={{ color: '#1890ff' }}
            >
              创建
            </Button>

            <Button
              key="terminate"
              type="link"
              size="small"
              onClick={() => handleTerminate(record)}
              danger
            >
              终止
            </Button>

          </Space>

        );
      },
    },
  ];

  // 处理新增
  const handleAdd = () => {
    setEditingRecord(null);
    setFormVisible(true);
  };

  // 处理创建（基于现有合同）
  const handleCreate = (record) => {
    // 基于现有合同信息创建新合同
    setEditingRecord({
      customerName: record.customerName,
      customerCode: record.customerCode,
      companyType: record.companyType,
      area: record.area,
      customerRating: record.customerRating,
      salesperson: record.salesperson,
      accountant: record.accountant,
      contactPerson: record.contactPerson,
      contactPhone: record.contactPhone,
      serviceItems: record.serviceItems,
      contractMonthlyFee: record.contractMonthlyFee,
      monthlyFee: record.monthlyFee,
      paymentPlan: record.paymentPlan,
      signDate: dayjs(),
    });
    setFormVisible(true);
  };

  // 处理解约
  const handleTerminate = (record) => {
    Modal.confirm({
      title: '确认解约',
      icon: <ExclamationCircleOutlined />,
      content: `确定要解约客户"${record.customerName}"的合同吗？解约后将无法恢复。`,
      okText: '确认解约',
      cancelText: '取消',
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          await terminateContract(record.id);
          message.success('解约成功');
          actionRef.current?.reload();
        } catch (error) {
          message.error('解约失败');
        }
      },
    });
  };

  // 处理恢复合同
  const handleRestore = (record) => {
    Modal.confirm({
      title: '确认恢复',
      icon: <ExclamationCircleOutlined />,
      content: `确定要恢复客户"${record.customerName}"的合同吗？恢复后合同状态将变为正常。`,
      okText: '确认恢复',
      cancelText: '取消',
      onOk: async () => {
        try {
          // 调用恢复合同的API，将状态改为正常
          await updateCustomerContract(record.id, {
            ...record,
            contractStatus: '正常'
          });
          message.success('恢复成功');
          actionRef.current?.reload();
        } catch (error) {
          message.error('恢复失败');
        }
      },
    });
  };

  // 处理表单提交
  const handleFormSubmit = async (values) => {
    try {
      const formattedValues = {
        ...values,
        signDate: values.signDate ? values.signDate.format('YYYY-MM-DD') : null,
      };

      await createCustomerContract(formattedValues);
      message.success('创建成功');

      setFormVisible(false);
      setEditingRecord(null);
      actionRef.current?.reload();
    } catch (error) {
      message.error('创建失败');
    }
  };

  // Tab配置
  const tabList = [
    {
      key: '正常',
      tab: '正常',
    },
    {
      key: '终止',
      tab: '终止',
    },
  ];

  return (
    <PageContainer
      header={{
        title: '客户合同',
        subTitle: '客户合同管理页面',
      }}
      tabList={tabList}
      tabActiveKey={activeTab}
      onTabChange={setActiveTab}
    >
      <ProTable
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}) => {
          try {
            const response = await getCustomerContracts({
              ...params,
              status: activeTab,
            });

            // 计算合计数据
            const data = response.data?.list || [];
            calculateSummary(data);

            return {
              data: data,
              success: response.success,
              total: response.data?.total || 0,
            };
          } catch (error) {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        rowKey="id"
        search={{
          filterType: 'light',
        }}
        scroll={{ x: 2000 }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
        columnsState={{
          value: columnsStateMap,
          onChange: setColumnsStateMap,
        }}
        toolBarRender={() => [
          <div key="summary" style={{
            display: 'flex',
            alignItems: 'center',
            gap: '24px',
            fontSize: '14px',
            color: '#666'
          }}>
            <span>
              <UserOutlined style={{ marginRight: '4px', color: '#1890ff' }} />
              合计：<strong style={{ color: '#1890ff' }}>{summaryData.totalCustomers}</strong> 户
            </span>
            <span>
              <DollarOutlined style={{ marginRight: '4px', color: '#52c41a' }} />
              合同月收费合计：<strong style={{ color: '#52c41a' }}>¥{summaryData.totalMonthlyFee.toLocaleString()}</strong> 元
            </span>
          </div>
        ]}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        dateFormatter="string"
      />

      <ContractForm
        visible={formVisible}
        title={editingRecord ? '基于现有合同创建' : '新建合同'}
        initialValues={{
          contractStatus: '正常',
          ...editingRecord,
        }}
        onCancel={() => {
          setFormVisible(false);
          setEditingRecord(null);
        }}
        onFinish={handleFormSubmit}
      />
    </PageContainer>
  );
};

export default CustomerContract; 